package com.huanghe.rabbitmq.all;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {

    private static Runnable runnable = new Runnable() {
        @Override
        public void run() {
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost("127.0.0.1");
            connectionFactory.setPort(5672);
            connectionFactory.setUsername("admin");
            connectionFactory.setPassword("admin");
            connectionFactory.setVirtualHost("/");

            Connection co = null;
            Channel channel = null;
            final String queueName = Thread.currentThread().getName();
            try {
                co = connectionFactory.newConnection("消费者");
                channel = co.createChannel();


                DeliverCallback deliver = new DeliverCallback() {
                    @Override
                    public void handle(String s, Delivery msg) throws IOException {
                        System.out.println(queueName + ": 收到消息" + new String(msg.getBody(), "UTF-8"));
                    }
                };

                channel.basicConsume(queueName, true, deliver, new CancelCallback() {
                    @Override
                    public void handle(String s) throws IOException {
                        System.out.println("发送失败");
                    }
                });
                System.out.println(queueName + ": 开始接收消息");
                System.in.read();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            } finally {
                if (channel != null && channel.isOpen()) {
                    try {
                        channel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (TimeoutException e) {
                        e.printStackTrace();
                    }
                }

                if (co != null && co.isOpen()) {
                    try {
                        co.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };


    public static void main(String[] args) {

        new Thread(runnable, "queue5").start();
        new Thread(runnable, "queue6").start();
        new Thread(runnable, "queue7").start();


    }
}
